<script setup lang="ts">
import { useLoadMore } from 'vue-request'
import { fetchPointsMallGoodsAPI } from '@/apis/fetchPointsMallGoods'
import { useUserInfoStore } from '@/store/userInfo'
import { exchangeGoodsAPI } from '@/apis/exchangeGoods'

import dialogIcon from '@/static/images/questionmark_colorful.png'

const router = useRouter()
const userInfoStore = useUserInfoStore()

// 分页列表数据
const { dataList, loading, loadingMore, noMore, loadMore } = useLoadMore<LoadMoreData<Goods>>(
  fetchData,
  { isNoMore: d => d?.list.length === d?.total },
)

// “加载更多”的状态
const loadMoreStatus = computed(() => {
  if (loadingMore.value)
    return 'loading'
  else if (noMore.value)
    return 'nomore'
  else
    return 'loadmore'
})

onShow(() => userInfoStore.update())
onReachBottom(() => loadMore())

/**
 * @description 分页服务函数
 */
async function fetchData(d?: LoadMoreData<Goods>): Promise<LoadMoreData<Goods>> {
  // 当前页数
  const _page = d?.page ? d.page + 1 : 1

  const res = await fetchPointsMallGoodsAPI(
    { page: _page.toString(), limit: '10' },
    userInfoStore.userInfo!.token!,
  )

  return {
    list: res.data?.data.data || [],
    page: _page,
    total: res.data?.data.total || 9999,
  }
}

const isShowDialog = ref(false)
const isShowSuccessDialog = ref(false)
const selectedGoods = ref<Goods | null>(null)

function handleViewRedeemRecord() {
  router.push('redeemRecord')
}

function handleViewPointsStatement() {
  router.push('pointsStatement')
}

function handleTapGoodsCard(id: string) {
  router.push({
    name: 'pointsMallGoodsDetail',
    params: { id },
  })
}

function handleRedeemGoods(goods: Goods) {
  selectedGoods.value = goods
  isShowDialog.value = true
}

function handleCancelRedeem() {
  isShowDialog.value = false
  selectedGoods.value = null
}

const handleConfirmRedeemGoods = useThrottleFn(async () => {
  uni.showLoading({ title: '加载中...' })
  const res = await exchangeGoodsAPI(
    { id: selectedGoods.value?.id.toString() || '' },
    userInfoStore.userInfo!.token!,
  )
  if (res.data?.code === 1) {
    await userInfoStore.update()
    isShowDialog.value = false
    isShowSuccessDialog.value = true
    selectedGoods.value = null
    uni.hideLoading()
  }
  else {
    uni.hideLoading()
    uni.showToast({ title: res.data?.msg, icon: 'none' })
  }
}, 1000)

function handleViewRedeemDescription() {
  router.push({
    name: 'protocol',
    params: { type: '积分商城兑换说明' },
  })
}
</script>

<template>
  <view class="min-h-screen bg-#F8F8F8">
    <view class="absolute left-0 top-0 h-815rpx w-screen from-#4999F7 to-#78D9FE to-opacity-0 bg-gradient-to-b" />
    <view class="relative z-1">
      <Spacer height="40" />
      <!-- Hero 卡片 START -->
      <view class="relative mx-auto h-352rpx w-700rpx">
        <image class="absolute left-0 top-0 z-1 h-352rpx w-700rpx" src="@/static/images/points_mall_card_bg.png" />
        <button
          class="absolute right-40rpx top-20rpx z-50 flex items-center border-2px border-#4999F7 rounded-full border-solid bg-white px-14rpx py-12rpx text-24rpx text-#4999F7 leading-32rpx"
          @tap="handleViewRedeemDescription"
        >
          <image class="h-21rpx w-21rpx" src="@/static/images/i.png" />
          <Spacer width="4" />
          兑换说明
        </button>
        <view class="relative z-2 h-352rpx flex flex-col justify-between">
          <view class="px-60rpx">
            <Spacer height="40" />
            <view class="text-28rpx text-#707070 leading-40rpx">
              我的积分
            </view>
            <view class="text-66rpx text-#333333 font-semibold leading-92rpx">
              {{ userInfoStore.userInfo?.score || '0' }}
            </view>
          </view>
          <view class="h-140rpx flex items-center">
            <view class="h-full w-full flex items-center justify-center" @tap="handleViewRedeemRecord">
              <image class="h-40rpx w-40rpx" src="@/static/images/points_mall_card_record.png" />
              <Spacer width="12" />
              <view class="text-32rpx text-#333333 font-medium">
                兑换记录
              </view>
            </view>
            <view class="h-full w-full flex items-center justify-center" @tap="handleViewPointsStatement">
              <image class="h-40rpx w-40rpx" src="@/static/images/points_mall_card_points.png" />
              <Spacer width="12" />
              <view class="text-32rpx text-#333333 font-medium">
                积分明细
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- Hero 卡片 END -->
    <Spacer height="60" />
    <view class="relative z-1 text-center text-32rpx text-#333333 font-semibold leading-45rpx">
      积分兑换
    </view>
    <Spacer height="40" />
    <!-- 网格 START -->
    <view class="relative z-1 grid grid-cols-2 gap-x-18rpx gap-y-24rpx px-24rpx">
      <view v-for="item in dataList" :key="item.id" class="flex flex-col items-center overflow-hidden rounded-20rpx bg-white" @tap="handleTapGoodsCard(item.id.toString())">
        <image class="h-250rpx w-342rpx bg-#F8F8F8" :src="withDomain(item.image)" />
        <view class="w-full px-12rpx py-16rpx">
          <view class="h-80rpx overflow-hidden text-28rpx font-medium leading-40rpx">
            {{ item.title }}
          </view>
          <Spacer height="12" />
          <view class="flex items-center justify-between rounded-15rpx from-#96CCFA bg-gradient-to-r px-16rpx py-20rpx">
            <view class="flex items-baseline text-33rpx text-#1B85FF leading-46rpx">
              {{ item.score }}积分
            </view>
            <button class="rounded-full from-#77DAFE to-#4999F7 bg-gradient-to-l px-24rpx py-10rpx text-28rpx text-white leading-28rpx" @tap.stop="handleRedeemGoods(item)">
              兑换
            </button>
          </view>
        </view>
      </view>
    </view>
    <!-- 网格 END -->
    <!-- 加载更多 -->
    <uv-load-more v-if="dataList.length > 3" :status="loadMoreStatus" @loadmore="loadMore" />
    <Spacer height="240" />
  </view>

  <uv-loading-page :loading="loading && !loadingMore" loading-text="加载中..." font-size="28rpx" loading-mode="spinner" />

  <uv-overlay :show="isShowDialog" @tap="handleCancelRedeem">
    <uv-transition mode="zoom-in" :show="isShowDialog">
      <view class="relative h-screen w-screen">
        <Dialog
          :icon="dialogIcon"
          title="确认兑换"
          :content="`是否花费${selectedGoods?.score}积分兑换该商品`"
          @cancel="handleCancelRedeem"
          @confirm="handleConfirmRedeemGoods"
        />
      </view>
    </uv-transition>
  </uv-overlay>
  <uv-overlay :show="isShowSuccessDialog" @tap="isShowSuccessDialog = false">
    <uv-transition mode="zoom-in" :show="isShowSuccessDialog">
      <view class="relative h-screen w-screen">
        <Dialog
          :icon="dialogIcon"
          title="兑换成功"
          hide-cancel-button
          @confirm="isShowSuccessDialog = false"
        />
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'pointsMall'
style:
  navigationBarTitleText: '积分商城'
layout: 'custom'
</route>
